package candidature.servlet;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.ResourceBundle;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import util.ServerResponse;

import business.bd.BD;
import business.dto.BasicDTO;
import business.dto.CandidatoDTO;
import business.view.CandidatoListRenderer;


/**
 * Servlet implementation class CandidatureServlet
 */
public class CandidatureServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private Logger logger=LogManager.getLogger(this.getClass());
    /**
     * Default constructor. 
     */
    public CandidatureServlet() {
        
    }

    
    
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException{
    	logger.info("BEGIN - CandidatureServlet");
    	
		response.setContentType("text/xml;charset=UTF-8");
	    PrintWriter out = response.getWriter();
    	
	    String action = request.getParameter("action");
	    String method = request.getParameter("method");
	    
	    //	PARAMETRO DI RICERCA SU FILE
	    String ricercaSuFile = request.getParameter("ricercaSuFile");
	    String textToSearch = request.getParameter("textToSearch");
	    
	    String dateStart1 = request.getParameter("dateStart1");
	    String dateStart2 = request.getParameter("dateStart2");
	    
	    
	    logger.debug("action - "+action);
	    logger.debug("method - "+method);
    	
	    HashMap parameterList = new HashMap();
	    
	    parameterList.put("servletName", this.getServletName());
	    parameterList.put("servletContext", this.getServletContext());
	 
        parameterList.put("request", request);
        
        parameterList.put("action", action);
        parameterList.put("method", method);
       
//        parameterList.put("rb", rb);
        
        if(ricercaSuFile!=null){
        	parameterList.put("ricercaSuFile", ricercaSuFile);
        	parameterList.put("textToSearch", textToSearch);
        	
        }
        
        if(dateStart1!=null && dateStart2!=null){
        	parameterList.put("dateStart1", dateStart1);
        	parameterList.put("dateStart2", dateStart2);
        }
        
        ServerResponse res = new ServerResponse(this.getServletName(), null, "OK");
        String responseCode="KO";
        
        try {
        	 BD businessDelegation = new BD(action+"."+method);
             businessDelegation.setPackageName("business.bl");
             
             res = (ServerResponse) businessDelegation.delegate(parameterList);
		} catch (Exception e) {
			logger.error("errore evocazione business delegation: ", e);
		}
        finally{
        	 ArrayList<BasicDTO> dtos = new ArrayList<BasicDTO>();
             ArrayList resultList = res.getData();
             
             ArrayList alternativeData =res.getAlternativedata(); 
             
             if (resultList != null){
                 for (int i = 0; i < resultList.size(); i++)
                 {
                     BasicDTO dto = (BasicDTO) resultList.get(i);
                     dtos.add(dto);
                 }
             }
        	
        	
        	  responseCode=res.getResponseCode();
        	  res = new ServerResponse(this.getServletName(), null, responseCode);
             
        	  StringBuilder sb = new StringBuilder();
        	  
        	  sb.append("<Data>");
        	  
        	  sb.append("<Candidati>");
              for (int i = 0; i < dtos.size(); i++)
              {
                  CandidatoDTO dto = (CandidatoDTO) dtos.get(i);

                  sb.append(dto.toString());
                  
              }
              sb.append("</Candidati>");
              
              
              
              if (alternativeData != null){
            	  dtos = new ArrayList<BasicDTO>();
                  for (int i = 0; i < alternativeData.size(); i++){
                      BasicDTO dto = (BasicDTO) alternativeData.get(i);
                      dtos.add(dto);
                  }
                  sb.append("<AltData>");
                  for (int i = 0; i < dtos.size(); i++)
                  {
                      CandidatoDTO dto = (CandidatoDTO) dtos.get(i);

                      sb.append(dto.toString());
                      
                  }
                  sb.append("</AltData>");
              }
              sb.append("</Data>");
              
              String relativeWebPath= "/xsl/candidatoList.xsl";
              String xslPath = getServletContext().getRealPath(relativeWebPath);
//              String xslPath="c:/apache-tomcat-6.0.36/wtpwebapps/gestione_candidature/xsl/"+"candidatoList.xsl";
              
              File f=new File(xslPath);
              
              
              logger.debug("xslPath: "+xslPath+" "+f.exists());
              CandidatoListRenderer clr=new CandidatoListRenderer(sb.toString(),xslPath);
              
              sb = new StringBuilder(clr.getHtml());
              
              int start=sb.indexOf("<?xml ");
              int end = sb.indexOf("?>");
              
              
              if (start>-1) {
  				
            	  logger.debug("start "+start);
                  logger.debug("end "+end);
                  
                  sb.replace(start,end+2 , "");
              
              }
              
              logger.debug(sb.toString());
              
//              res.addData(clr.getHtml());
        	  
              res.addData(sb.toString());
              
              logger.debug(res);
              
              out.print(res);
              out.close();
        }
      
      
        
//        parameterList.put("resourceBundle", rb);
	    
	    
    	logger.info("END - CandidatureServlet");
    }
    
    
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

}
